package com.zh.freechat.domain.validcode;

import com.zh.mycommon.util.MyIdGenerator;
import com.zh.mycommon.util.RandomCodeUtil;
import com.zh.mycommon.value.Tuple2;
import com.zh.webcommon.common.exception.ServiceException;
import com.zh.webcommon.common.exception.errorcode.BizError;
import com.zh.webcommon.common.support.RedisCacheHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;

import static com.zh.freechat.common.CacheKeysConst.CAPTCHA_CODE_KEY;

/**
 * 验证码实现处理
 *
 * @author ruoyi
 */
@Service
public class ValidateCodeService {

    /**
     * 生成手机验证码、邮箱验证码 等
     *
     * @param codeType
     * @return Tuple[uuid, Code]
     */
    public Tuple2<String, String> createSmsCode(String codeType) {
        // 生成验证码
        final String code;
        if ("number".equals(codeType)) {
            code = RandomCodeUtil.getNumberCode(4);
        } else {
            code = RandomCodeUtil.getCharacterCode(8, false);
        }

        //保存到服务端
        return new Tuple2<>(save(code), code);
    }


    /**
     * 校验验证码
     */
    public void validateSmsCode(String code, String uuid) {
        if (!StringUtils.hasText(code)) {
            throw new IllegalArgumentException("code不能为空");
        }
        if (!StringUtils.hasText(uuid)) {
            throw new IllegalArgumentException("uuid不能为空");
        }

        String verifyKey = CAPTCHA_CODE_KEY + uuid;
        String captcha = RedisCacheHelper.getCacheRedis(verifyKey);

        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException(BizError.DEFAULT_ERROR, "验证码错误");
        }
        //验证成功后清除验证码
        RedisCacheHelper.removeCacheRedis(verifyKey);
    }

    private String save(String code) {
        // 保存验证码信息
        String uuid = MyIdGenerator.uuid();
        String verifyKey = CAPTCHA_CODE_KEY + uuid;

        RedisCacheHelper.cacheRedis(verifyKey, code, Duration.ofMinutes(3));
        return uuid;
    }

}
